package com.theatre.userservice.interceptor;

import com.theatre.userservice.Constant.JwtClaimsConstant;
import com.theatre.userservice.Controller.contxet.BaseContext;
import com.theatre.userservice.properties.JwtProperties;
import com.theatre.userservice.model.vo.Result;
import com.theatre.userservice.model.vo.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import com.fasterxml.jackson.databind.ObjectMapper;
@Slf4j
@Component
public class JwtTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader(jwtProperties.getUserTokenName());
        if (token == null || token.isEmpty()) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(new ObjectMapper().writeValueAsString(Result.error("未登录或Token为空")));
            return false;
        }
        log.info("JwtTokenInterceptor 被调用, 请求路径：{}", request.getRequestURI());

        try {
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);

            // 获取 roleId 并存入 ThreadLocal 中
            Long roleId = Long.valueOf((Integer) claims.get(JwtClaimsConstant.ROLE_ID));
            BaseContext.setCurrentId(roleId);
            BaseContext.setUserId(Long.valueOf((Integer) claims.get(JwtClaimsConstant.ID)));
            return true;

        } catch (Exception e) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(new ObjectMapper().writeValueAsString(Result.error("检验Token时出现异常")));
            return false;
        }
    }
}
